package com.jqq.arrays_;

import java.util.Arrays;
import java.util.Comparator;

/**
 * @author 姬倩倩
 * @version 1.0
 */
public class ArrayExercise {
    public static void main(String[] args) {
        Book[] books = new Book[4];
        books[0] = new Book("红楼梦",100);
        books[1] = new Book("金瓶梅",90);
        books[2] = new Book("青年文摘",5);
        books[3] = new Book("Java从入门到放弃",300);

        Arrays.sort(books, new Comparator<Book>() {
            @Override
            public int compare(Book o1, Book o2) {
                double priceDiff = o2.getPrice()-o1.getPrice();
                if(priceDiff < 0){
                    return -1;
                } else if(priceDiff > 0){
                    return 1;
                } else{
                    return 0;
                }
            }
        });
        System.out.println("==按价格从大到小排序===");
        for (Book book : books) {
            System.out.println(book);
        }

        System.out.println("==按价格从小到大排序===");
        Arrays.sort(books, new Comparator<Book>() {
            @Override
            public int compare(Book o1, Book o2) {
                double priceDiff = o1.getPrice()-o2.getPrice();
                if(priceDiff < 0){
                    return -1;
                } else if(priceDiff > 0){
                    return 1;
                } else{
                    return 0;
                }
            }
        });
        for (Book book : books) {
            System.out.println(book);
        }

        System.out.println("==按书名长度从大到小排序===");
        Arrays.sort(books, new Comparator<Book>() {
            @Override
            public int compare(Book o1, Book o2) {
                return o2.getName().length()-o1.getName().length();
            }
        });
        for (Book book : books) {
            System.out.println(book);
        }
    }
}
class Book{
    private String name;
    private double price;

    public Book(String name, int price) {
        this.name = name;
        this.price = price;
    }

    public double getPrice() {
        return price;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}